package com.hub.netty.base.handler;

import com.alibaba.fastjson2.JSONObject;
import com.hub.netty.base.domain.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
import lombok.RequiredArgsConstructor;

/**
 * 消息编码器
 */
@RequiredArgsConstructor
public class MessageEncodeHandler extends MessageToByteEncoder<Message> {

    // 数据分割符
    private final String delimiter;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf out) throws Exception {
        out.writeBytes((JSONObject.toJSONString(message) + delimiter).getBytes(CharsetUtil.UTF_8));
    }
}
